package com.maben.mqtt.test001;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import javax.net.ssl.SSLSocketFactory;

/**
 * 测试普通TCP连接
 */
public class Test001 {
    public static void main(String[] args)throws Exception {
        tcpTest();

//        sslTest();
    }

    /**
     * ssl连接，因为没有文件先不测
     */
    private static void sslTest()throws Exception {
        // 设置 SSL/TLS 连接地址
        String broker = "ssl://broker.emqx.io:8883";
        String clientId = "publish_client";
        // 设置 socket factory
        String caFilePath = "/cacert.pem";
        String clientCrtFilePath = "/client.pem";
        String clientKeyFilePath = "/client.key";

        MqttConnectOptions options = new MqttConnectOptions();
        SSLSocketFactory socketFactory = SSLUtils.getSocketFactory(caFilePath, clientCrtFilePath, clientKeyFilePath, "");
        options.setSocketFactory(socketFactory);
        //同步调用客户端，使用阻塞方法通信。
        MqttClient client = new MqttClient(broker,clientId);
        client.connect(options);
        System.out.println("********连接成功********");

    }

    /**
     * 普通tcp连接，最常用
     */
    private static void tcpTest()throws Exception {
        String broker = "tcp://broker.emqx.io:1883";
        String username = "emqx";
        String password = "public";
        String clientId = "publish_client";

        //同步调用客户端，使用阻塞方法通信。
        MqttClient client = new MqttClient(broker, clientId, new MemoryPersistence());
        /*
        MqttConnectOptions: 连接选项，用于指定连接的参数，下面列举一些常见的方法。
            setUserName: 设置用户名
            setPassword: 设置密码
            setCleanSession: 设置是否清除会话
            setKeepAliveInterval: 设置心跳间隔
            setConnectionTimeout: 设置连接超时时间
            setAutomaticReconnect: 设置是否自动重连
         */
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        client.connect(options);
        System.out.println("********连接成功********");
    }
}
